from cvsmatchform import Ui_CvsMatchForm
import sys, ConfigParser, _pg, pickle
from PyQt4 import QtCore, QtGui

class AliasItem(QtGui.QListWidgetItem):
	def __init__(self, parent, email, name, personid, sent):
		QtGui.QListWidgetItem.__init__(self, parent, 0)
		self.name = name.strip()
		self.email = email.strip()
		self.personid = personid
		self.sent = sent
		self.string = str(self)
		self.setText(self.string)
		
		
	def __str__(self):
		if self.name:
			return "%s <%s> id:%i sent:%i" % (self.name, self.email, self.personid, self.sent)
		else:
			return "<%s> id:%i sent:%i" % (self.email, self.personid, self.sent)



class CvsMatcher(QtGui.QMainWindow, Ui_CvsMatchForm):
	def __init__(self, configFile):
		self.configFile = configFile
		QtGui.QMainWindow.__init__(self)
		self.setupUi(self)
		
		self.connect(self.searchLineEdit, QtCore.SIGNAL("textEdited(const QString &)"), self.search)
		self.connect(self.commitButton, QtCore.SIGNAL("clicked()"), self.commitMatch)

		self.connect(self.addButton, QtCore.SIGNAL("clicked()"), self.addEntry)
		
		
		self.test()
		
	def test(self):
		self.connectToDBSlot()
		
	def connectToDBSlot(self):
		cp = ConfigParser.ConfigParser()
		cp.read(self.configFile)
		
		
		#extract sql login info and connect to database
		dbName = cp.get('config', 'dbName')
		dbHost = cp.get('config', 'dbHost')
		dbUser = cp.get('config', 'dbUser')
		dbPass = cp.get('config', 'dbPass')

		try:
			print "connecting to database..."
			self.db = _pg.connect(dbname=dbName,host=dbHost,passwd=dbPass,user=dbUser)
			print "...OK!"
		except _pg.InternalError:	
			print "Could not connect to database", dbName
			sys.exit(2)
		sql = """select count(*) as sent, aliases.email, aliases.name, aliases.personid from aliases, aliases as aliases2,
			messages where messages.senderaliasid = aliases2.aliasid and aliases2.personid = aliases.personid
			group by aliases.email, aliases.name, aliases.personid"""


		nameset = set()			
		self.aliasList = []
		for sent, email, name, personid in self.db.query(sql).getresult():
			nameset.add(name)
			item = AliasItem(self.aliasListWidget, email, name, personid, sent)
			self.aliasList.append(item)

		sql = "select name, personid from people"
		for name, personid in self.db.query(sql).getresult():
			if not name in nameset:
				item = AliasItem(self.aliasListWidget, "NONE", name, personid, 0)
				self.aliasList.append(item)
			
		self.cvsList = []
		tmplist = []
		for count, name, repid in self.db.query("""select count(*) as count, repname, repusers.repid from repusers,  files
			where files.repid = repusers.repid and personid is NULL group by repusers.repid, repusers.repname""").getresult():
			tmplist.append(name + " : " + str(count))
		tmplist.sort()
		for name in tmplist:
			item = QtGui.QListWidgetItem(name, self.cvsListWidget, 0)
			self.cvsList.append(item) 
			
	def search(self, text):
		text = str(text).strip()
		#if the text is empty then make everything visible
		if not text:
			for item in self.aliasList:
				self.aliasListWidget.setItemHidden(item, False)
		else:
			strings = text.split()
			for item in self.aliasList:
				itemString = item.string
				matches = True
				for string in strings:
					if not string in itemString:
						matches = False
				self.aliasListWidget.setItemHidden(item, not matches) 
					
				
		print "searching for text:", text
		
	def commitMatch(self):
		print "clicked"
		if self.cvsListWidget.currentItem() == None or self.cvsListWidget.isItemHidden(self.cvsListWidget.currentItem()):
			QtGui.QMessageBox.warning(self, "Invalid Selection", """<qt>There is not currently selected cvs account
			for the operation requested.  Please select a cvs account and try again</qt>""", QtGui.QMessageBox.Ok,
			QtGui.QMessageBox.NoButton)
			return
		repname = str(self.cvsListWidget.currentItem().text()).split(":")[0].strip()
		personid = self.aliasListWidget.currentItem().personid
		
		sql = "UPDATE repusers SET personid = %i where repname = '%s'" % (personid, repname)
		
		status = QtGui.QMessageBox.question(self, "Commit Match?", """<qt>Are you sure that you want to commit the match that %s
			matches %s</qt>""" % (repname, self.aliasListWidget.currentItem().name), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
		if status == QtGui.QMessageBox.Yes:
			print "committing sql", sql
			self.db.query(sql)
			
			self.cvsListWidget.setItemHidden(self.cvsListWidget.currentItem(), True)

	def addEntry(self):
		print "add entry"
		if self.cvsListWidget.currentItem() == None or self.cvsListWidget.isItemHidden(self.cvsListWidget.currentItem()):
			QtGui.QMessageBox.warning(self, "Invalid Selection", """<qt>There is not currently selected cvs account
			for the operation requested.  Please select a cvs account and try again</qt>""", QtGui.QMessageBox.Ok,
			QtGui.QMessageBox.NoButton)
			return
		repname = str(self.cvsListWidget.currentItem().text()).split(":")[0].strip()
		newname = str(self.addLineEdit.text())

		status = QtGui.QMessageBox.question(self, "Add Entry?", """<qt>Are you sure that you want to add an entry into people for %s
			with name %s</qt>""" % (repname, newname), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
		if status == QtGui.QMessageBox.Yes:
			sql = "insert into people (name, isdev) values ('%(newname)s', true)" % locals()
			print sql
			self.db.query(sql)
			sql = "update repusers set personid = (select personid from people where name ='%(newname)s') where repname = '%(repname)s'" % locals()
			print sql
			self.db.query(sql)
			self.cvsListWidget.setItemHidden(self.cvsListWidget.currentItem(), True)

			
def runGui():
	app = QtGui.QApplication(sys.argv)
	#first arg is the path to the config file
	cvsMatcher = CvsMatcher(sys.argv[1])
	cvsMatcher.show()
	app.exec_()
			
				
if __name__ == "__main__":
	runGui()
